from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_
from app.database import get_db
from app.models.spot import Spot
from app.models.order import Order
from app.models.user import User
from typing import Optional

router = APIRouter()

@router.get("")
def get_spots(
    db: Session = Depends(get_db),
    search: Optional[str] = None,
    type: Optional[str] = None,
    min_rating: Optional[float] = None,
    sort_by: Optional[str] = Query(None, enum=["rating", "price", "-rating", "-price"]),
):
    query = db.query(Spot)
    
    # 搜索
    if search:
        query = query.filter(
            or_(
                Spot.name.ilike(f"%{search}%"),
                Spot.location.ilike(f"%{search}%"),
                Spot.description.ilike(f"%{search}%")
            )
        )
    
    # 类型筛选
    if type and type != 'all':
        query = query.filter(Spot.type == type)
    
    # 评分筛选
    if min_rating:
        query = query.filter(Spot.rating >= min_rating)
    
    # 排序
    if sort_by:
        if sort_by == "rating":
            query = query.order_by(Spot.rating.asc())
        elif sort_by == "-rating":
            query = query.order_by(Spot.rating.desc())
        elif sort_by == "price":
            query = query.order_by(Spot.price.asc())
        elif sort_by == "-price":
            query = query.order_by(Spot.price.desc())
    
    spots = query.all()
    return [
        {
            "id": spot.id,
            "name": spot.name,
            "description": spot.description,
            "location": spot.location,
            "type": spot.type,
            "open_time": spot.open_time,
            "price": spot.price,
            "images": spot.images,
            "inventory": spot.inventory,
            "rating": spot.rating
        }
        for spot in spots
    ]

@router.get("/{spot_id}")
def get_spot(spot_id: int, db: Session = Depends(get_db)):
    """获取单个景点详情"""
    spot = db.query(Spot).filter(Spot.id == spot_id).first()
    if not spot:
        raise HTTPException(status_code=404, detail="景点不存在")
    
    # 获取景点评价
    reviews = (
        db.query(Order)
        .filter(
            Order.spot_id == spot_id,
            Order.rating.isnot(None)
        )
        .join(User)
        .order_by(Order.commented_at.desc())
        .all()
    )
    
    return {
        "id": spot.id,
        "name": spot.name,
        "description": spot.description,
        "location": spot.location,
        "type": spot.type,
        "open_time": spot.open_time,
        "price": spot.price,
        "images": spot.images,
        "inventory": spot.inventory,
        "rating": spot.rating,
        "reviews": [{
            "id": review.id,
            "rating": review.rating,
            "comment": review.comment,
            "commented_at": review.commented_at,
            "user": {
                "username": review.user.username if not review.is_anonymous else "匿名用户"
            }
        } for review in reviews]
    } 